package com.cis.fingerprint.utils;

import java.nio.ByteBuffer;
import java.util.Locale;

/**
 * Byte转换工具
 */
public class ByteUtils {


    /**
     * 十六进制字符串转byte[]
     *
     * @param hex 十六进制字符串
     * @return byte[]
     */
    public static byte[] hexStr2Byte(String hex){
        if (hex == null){
            return new byte[]{};
        }

        //奇数位补0
        if (hex.length() % 2 != 0){
            hex = "0" + hex;
        }
        int length = hex.length();
        ByteBuffer buffer = ByteBuffer.allocate(length / 2);
        for (int i = 0; i < length; i++) {
            String hexString = hex.charAt(i) + "";
            i++;
            hexString += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexString, 16);
            buffer.put(b);
        }
        return buffer.array();
    }

    /**
     * byte[]转十六进制字符串
     *
     * @param array
     * @return
     */
    public static String byteArrayToHexString(byte[] array) {
        if (array == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            buffer.append(byteToHex(array[i]));
        }
        return buffer.toString();
    }

    public static String byteToHex(byte b){
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() == 1){
            hex = '0' + hex;
        }
        return hex.toUpperCase(Locale.getDefault());
    }

    /**
     * 2位byte[]转int
     */
    public static int towByteArrayToInt(byte[] array){
        return array[1] + (array[0] << 8);
    }

    public static byte[] intToTowByteArray(int value){
        byte[] array = new byte[2];
        array[0] = (byte) ((value >> 8) & 0xff);
        array[1] = (byte) (value & 0xff);
        return array;
    }
}
